<?php

namespace app\api\controller\v1\activity;

use app\Request;
use app\services\activity\score\StoreScoreTaskServices;
use app\services\activity\score\StoreScoreTaskRecordServices;
use app\services\user\UserServices;

class StoreScoreTaskController
{
    protected $services;

    public function __construct(StoreScoreTaskServices $services)
    {
        $this->services = $services;
    }

    /**
     * @param Request $request
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function list(Request  $request){
        $uid = (int)$request->uid();

        $list = $this->services->getTaskList();

        /** @var StoreScoreTaskRecordServices $service */
        $storeScoreTaskRecordServices = app()->make(StoreScoreTaskRecordServices::class);
        $finish_list = $storeScoreTaskRecordServices->getUserTasksFinishNumber($uid);

        foreach ($list['list'] as $key => $task){
            $list['list'][$key]['is_finish'] = 1;
            foreach ($finish_list as $record){
                if($task['id'] == $record['task_id']){
                    if($task['finish_num'] <= $record['finish_num']){
                        $list['list'][$key]['is_finish'] = 0;
                    }
                }
            }
            unset($list['list'][$key]['finish_num']);
        }

        /** @var UserServices $userServices */
        $userServices = app()->make(UserServices::class);
        $user = $userServices->getUserInfo($uid);

        $list['info'] = [
            'integral' => $user->integral,
        ];
        return app('json')->success($list);
    }

    /**
     * 完成积分任务
     * @param Request $request
     * @return mixed
     */
    public function finish(Request $request)
    {
        $data = $request->getMore([
            ['task_id', 0],
        ]);
        if (!$data['task_id']) {
            return app('json')->fail(400802);
        }
        $user = $request->user()->toArray();
        $this->services->finish($data['task_id'],$user);
        return app('json')->success($data);
    }
}
